from pathlib import Path
import json
import logger
import utils

translations_root=Path("translations")

# 全局翻译文件的路径
public_file = translations_root/"public.json"
# 全局翻译文件
public_translations = utils.read_data(public_file)

def get_translation(text:str,translations:dict,translations_file:str,update_translations:bool,is_public:bool)->str:
    """获取翻译文件，并在更新翻译文件时生成日志"""
    # 查看翻译文件内有没有对应翻译
    if text in translations:
        return translations[text]
    elif text in public_translations:
        return public_translations[text]
    # 当没有对应的翻译时，判断是否需要更新翻译文件
    if update_translations:
        # 判断是要更新到全局翻译文件还是专用翻译文件
        if is_public:
            public_translations[text]=text
            logger.log(f"已添加:{text}",f"logs/translations/public.json.log")
        else:
            translations[text]=text
            logger.log(f"已添加:{text}", f"logs/{translations_file}.log")
    return text

def translate_map_data(data:dict,map:str,is_resources,update_translations=False):
    # 载入专用翻译文件
    translations_file=translations_root/"map-data"/f"{map}.json"
    if translations_file.exists():
        translations=json.loads(translations_file.read_text(encoding="utf-8"))
    else:
        translations={}
    # 遍历数据，然后翻译
    for item in data:
        item["name"]=get_translation(item["name"],translations,f"{map}.json",update_translations,is_resources)
        for dot in item["dots"]:
            dot["caption"] = get_translation(dot["caption"],translations,f"{map}.json",update_translations,False)
            dot["note"] = get_translation(dot["note"],translations,f"{map}.json",update_translations,False)
    # 如果指定要更新翻译，则将修改后的翻译文件保存到本地
    if update_translations:
        utils.save_data(translations, translations_file)
        utils.save_data(public_translations, public_file)

def translate_items(items:dict,update_translations:bool=False):
    """ 翻译物品数据 """
    # 载入专用翻译文件
    translations_file = translations_root/"items.json"
    translations = utils.read_data(translations_root/"items.json")
    # 遍历数据，然后进行翻译
    for item in items.values():
        # 翻译物品的名称
        item["name"] = get_translation(item["name"], translations, translations_file, update_translations, True) # 翻译物品的名字
        # 翻译物品的描述
        if "description" in item:
            item["description"] = get_translation(item["description"], translations, translations_file, update_translations, False) # 翻译物品的描述
        # 翻译生成代码中各个不同种类的名称
        if "spawnCommands" in item:
            for spawn_command in item["spawnCommands"]:
                spawn_command["name"] = get_translation(spawn_command["name"], translations, translations_file, update_translations, True)
        if "ingredientses" in item and item["ingredientses"] is not None:
            for ingredients in item["ingredientses"]:
                ingredients["name"] = get_translation(ingredients["name"], translations, translations_file, update_translations, True)
    # 如果指定要更新翻译，则将修改后的翻译文件保存到本地
    if update_translations:
        utils.save_data(translations, translations_file)
        utils.save_data(public_translations, public_file)

def translate_creatures(creatures:dict,update_translations=False):
    """ 翻译生物数据 """
    for creature in creatures.values():
        # 载入专用翻译文件
        translations_file = translations_root/f"creatures/{creature['id']}.json"
        translations = utils.read_data(translations_file)
        # 生物的名字
        creature["name"] = get_translation(creature["name"], translations, translations_file, update_translations, True)
        
        # 状态
        for stat in creature["stats"]:
            # 翻译种类名
            stat["name"] = get_translation(stat["name"], translations, translations_file, update_translations, True)
            # 翻译属性名
            for attribute in stat["attributes"].values():
                attribute["name"] = get_translation(attribute["name"], translations, translations_file, update_translations, True)
        # 翻译栖息地
        for habitat in creature["habitats"]:
            habitat["species"] = get_translation(habitat["species"], translations, translations_file, update_translations, True)
            for spawn_data in habitat["spawningData"]:
                spawn_data["mapName"] = get_translation(spawn_data["mapName"], translations, translations_file, update_translations, True)
        # 翻译生成代码
        for spawn_command in creature["spawnCommands"]:
            spawn_command["name"] = get_translation(spawn_command["name"], translations, translations_file, update_translations, True)
        # 翻译图鉴文本
        for dossier_text in creature["dossierTexts"]:
            # 图鉴生物在游戏中的名称
            dossier_text["name"] = get_translation(dossier_text["name"], translations, translations_file, update_translations, True)
            # 笔记右上角的便笺
            if "formalName" in dossier_text:
                dossier_text["formalName"] = get_translation(dossier_text["formalName"], translations, translations_file, update_translations, False)
            if "time" in dossier_text:
                dossier_text["time"] = get_translation(dossier_text["time"], translations, translations_file, update_translations, True)
            if "temperament" in dossier_text:
                dossier_text["temperament"] = get_translation(dossier_text["temperament"], translations, translations_file, update_translations, True)
            if "diet" in dossier_text:
                dossier_text["diet"] = get_translation(dossier_text["diet"], translations, translations_file, update_translations, True)
            if "modelNumber" in dossier_text:
                dossier_text["modelNumber"] = get_translation(dossier_text["modelNumber"], translations, translations_file, update_translations, False)
            if "height" in dossier_text:
                dossier_text["height"] = get_translation(dossier_text["height"], translations, translations_file, update_translations, False)
            if "weight" in dossier_text:
                dossier_text["weight"] = get_translation(dossier_text["weight"], translations, translations_file, update_translations, False)
            if "threatLevel" in dossier_text:
                dossier_text["threatLevel"] = get_translation(dossier_text["threatLevel"], translations, translations_file, update_translations, False)
            if "primaryFunction" in dossier_text:
                dossier_text["primaryFunction"] = get_translation(dossier_text["primaryFunction"], translations, translations_file, update_translations, False)
            # 笔记正文内容
            if "observations" in dossier_text:
                dossier_text["observations"] = get_translation(dossier_text["observations"], translations, translations_file, update_translations, False)
            if "history" in dossier_text:
                dossier_text["history"] = get_translation(dossier_text["history"], translations, translations_file, update_translations, False)
            if "wild" in dossier_text:
                dossier_text["wild"] = get_translation(dossier_text["wild"], translations, translations_file, update_translations, False)
            if "info" in dossier_text:
                dossier_text["info"] = get_translation(dossier_text["info"], translations, translations_file, update_translations, False)
            if "domesticated" in dossier_text:
                dossier_text["domesticated"] = get_translation(dossier_text["domesticated"], translations, translations_file, update_translations, False)
            for i in range(1,5):
                if f"head{i}" in dossier_text:
                    dossier_text[f"head{i}"] = get_translation(dossier_text[f"head{i}"], translations, translations_file, update_translations, False)
                if f"info{i}" in dossier_text:
                    dossier_text[f"info{i}"] = get_translation(dossier_text[f"info{i}"], translations, translations_file, update_translations, False)
        # 生物的小知识
        for trivium in creature["trivia"]:
            trivium["content"] = get_translation(trivium["content"], translations, translations_file, update_translations, False)
            for i in range(len(trivium["notes"])):
                trivium["notes"][i] = get_translation(trivium["notes"][i], translations, translations_file, update_translations, False)
        # 翻译攻击
        for attack in creature["attacks"]:
            attack["name"] = get_translation(attack["name"], translations, translations_file, update_translations, False)
            # 翻译攻击的描述
            for i in range(len(attack["descriptions"])):
                attack["descriptions"][i] = get_translation(attack["descriptions"][i], translations, translations_file, update_translations, False)
            # 翻译键位
            for key in attack["keys"]:
                key["name"] = get_translation(key["name"], translations, translations_file, update_translations, True)
        # 翻译相册中相片的标题
        for photo in creature["gallery"]:
            photo["caption"] = get_translation(photo["caption"], translations, translations_file, update_translations, False)
        # 翻译更新日志
        for changelog in creature["changelogs"]:
            for i in range(len(changelog["changes"])):
                changelog["changes"][i] = get_translation(changelog["changes"][i], translations, translations_file, update_translations, False)
        # 保存专用翻译文件
        if update_translations:
            utils.save_data(translations, translations_file)
    # 保存通用翻译文件
    if update_translations:
        utils.save_data(public_translations, public_file)

def translate_taming_foods(taming_foods,update_translations=False):
    """ 翻译驯服食物的名字 """
    translations_file = Path("translations/taming-foods.json")
    translations = utils.read_data(translations_file)
    for taming_food in taming_foods.values():
        taming_food["name"] = get_translation(taming_food["name"], translations, translations_file, update_translations, False)
    if update_translations:
        utils.save_data(translations, translations_file)

def translate_server_rates(server_rates:list,update_translations=False):
    # 载入专用翻译文件
    translations_file = translations_root/"server-rates.json"
    translations = utils.read_data(translations_file)
    # 遍历数据，然后进行翻译
    for server_rate in server_rates:
        server_rate["serverName"] = get_translation(server_rate["serverName"], translations, translations_file, update_translations, False)
        for rate in server_rate["rates"]:
            for i in range(len(rate["data"])):
                rate["data"][i] = get_translation(rate["data"][i], translations, translations_file, update_translations, False)
    # 如果指定要更新文件，则将更新之后的文件存到本地
    if update_translations:
        utils.save_data(translations, translations_file)

def translate_status_effects(status_effects:list,update_translations=False):
    """ 翻译状态效果数据 """
    # 载入专用翻译文件
    translations_file = translations_root/"status-effect.json"
    translations=utils.read_data(translations_file)
    # 遍历数据，进行翻译
    for status_effect in status_effects:
        status_effect["name"]=get_translation(status_effect["name"], translations, translations_file, update_translations, True)
        if "message" in status_effect:
            status_effect["message"] = get_translation(status_effect["message"], translations, translations_file, update_translations, False)
        if "hudText" in status_effect:
            status_effect["hudText"] = get_translation(status_effect["hudText"], translations, translations_file, update_translations, False)
        if "infomation" in status_effect:
            status_effect["infomation"] = get_translation(status_effect["infomation"], translations, translations_file, update_translations, False)
        if "notes" in status_effect:
            for i in range(len(status_effect["notes"])):
                status_effect["notes"][i] = get_translation(status_effect["notes"][i], translations, translations_file, update_translations, False)
    # 如果指定要更新翻译文件，则保存更新后的文件
    if update_translations:
        utils.save_data(translations, translations_file)
        utils.save_data(public_translations, public_file)